<template>
  <div class="app-container">
    <div class="title">试题管理</div>
    <div class="table">
      <div class="left-tools">
        <el-button type="primary" @click="addQuestion" size="mini">
          <router-link :to="{ name: 'addSctk', params: { id: id } }" class="link">
            添加试题
          </router-link>
        </el-button>
        <el-select v-model="queryParams.type" placeholder="请选择题型" class="title-button" size="mini">
          <el-option label="全部题型" value=""></el-option>
          <el-option label="单选题" value="1"></el-option>
          <!-- <el-option label="多选题" value="2"></el-option>
      <el-option label="判断题" value="3"></el-option>
      <el-option label="填空题" value="4"></el-option>
      <el-option label="简答题" value="5"></el-option> -->
        </el-select>
        <el-select v-model="queryParams.fk_t_sctk_chapter_id" placeholder="请选择" class="title-button" size="mini">
          <el-option label="全部章节" :value="''">
            <span>全部章节</span>
          </el-option>
          <el-option label="无章节" :value="-1">
            <span>无章节</span>
          </el-option>
          <el-option v-for="item in flatChapters" :key="item.id" :label="item.name" :value="item.id">
            <span :style="{ paddingLeft: item.level * 20 + 'px' }">{{ item.name }}</span>
          </el-option>

        </el-select>
        <el-dropdown @command="handleCommand">
          <el-button size="mini" class="title-button">更多操作<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="batchDelete">批量删除</el-dropdown-item>
            <el-dropdown-item command="batchUpdateChapter">批量更换章节</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <!-- 搜索框单独靠右 -->
      <div class="search-container">
        <el-input v-model="queryParams.topic" placeholder="请输入内容" size="mini" style="width: 300px; margin-left: 10px;"
          @keyup.enter.native="searchQuestions">
          <i slot="suffix" class="el-input__icon el-icon-search" @click="searchQuestions"></i>
        </el-input>
      </div>
    </div>


    <el-table :data="questions" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      :expand-row-keys="expandedRows" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="题干" class="topic-container">
              <span>{{ props.row.topic }}</span>
              <ul class="no-bullets">
                <li v-for="option in parseOptions(props.row.options)" :key="option.key" class="option-item">
                  {{ option.key }}.{{ option.value }}
                </li>
              </ul>
            </el-form-item>
            <el-form-item label="答案">
              <span>{{ props.row.answer }}</span>
            </el-form-item>
            <!-- <el-form-item label="解析">
              <span>{{ props.row.analysis }}</span>
            </el-form-item> -->
          </el-form>
        </template>
      </el-table-column>
      <el-table-column :formatter="(row, column, cellValue) => typeName(row.type)" label="题型"
        width="80"></el-table-column>
      <el-table-column type="index" label="编号" width="60"></el-table-column>
      <el-table-column prop="topic" label="题目" show-overflow-tooltip width="280"></el-table-column>
      <el-table-column prop="answer" label="答案" width="160"></el-table-column>
      <el-table-column prop="chapterName" :formatter="(row, column, cellValue) => cellValue || '--'" label="章节"
        width="200" class-name="custom-padding"></el-table-column>
      <el-table-column :formatter="(row, column, cellValue) => difficultyName(row.difficulty)" label="难易程度"
        width="200"></el-table-column>
      <el-table-column prop="updatetime" label="编辑时间" width="200"></el-table-column>
      <el-table-column label="操作" width="150">

        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column>
        <!-- 占空位 -->
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination @size-change="changePageSize" @current-change="changePageIndex"
        :current-page="queryParams.pageIndex" :page-sizes="[10, 20, 50]" :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <batchUpdateChapter v-if="id !== null" :show-dialog.sync="updateChapterShowDialog" :title="updateChapterdialogTitle"
      :fk_t_sctk_id="Number(id)" :ids="updateChapterIds" @submit="getQuesstionBankList">
    </batchUpdateChapter>
    <updateQuestion v-if="id !== null" :show-dialog.sync="updateQuestionShowDialog" :title="updateQuestiondialogTitle"
      :fk_t_sctk_id="Number(id)" :fk_t_sctk_question_id="Number(updateQuestiondialogId)" @submit="getQuesstionBankList">
    </updateQuestion>
  </div>
</template>
<script>

import { getQuesstionBankList, deleteQuestion } from '@/api/quesstionBank';
import { getSctktChapterList } from '@/api/sctkChapter'
import { transListToTreeDataOnChapter } from '@/utils'
import batchUpdateChapter from '@/components/batchUpdateChapter'
import updateQuestion from '@/components/updateQuestion'
export default {
  name: 'questions',
  components: {
    batchUpdateChapter, updateQuestion
  },
  created() {
    //访问后端客户接口
    this.id = this.$route.params.id;
    this.getQuesstionBankList();
    this.getChapters(); // 在组件创建时调用获取章节的方法

  },
  computed: {
    // 将嵌套数据转换为扁平数组
    flatChapters() {
      const result = [];

      function flatten(items, level = 0) {
        for (const item of items) {
          const newItem = { ...item, level }; // 添加层级信息
          result.push(newItem);
          if (item.children && item.children.length > 0) {
            flatten(item.children, level + 1); // 递归处理子级
          }
        }
      }

      flatten(this.chapters); // 开始扁平化处理
      return result;
    }
  },
  watch: {
    'queryParams.fk_t_sctk_chapter_id'(newVal) {

      this.getQuesstionBankList();
    },
    'queryParams.type'(newVal) {
      this.getQuesstionBankList();
    },
  },

  data() {
    return {
      updateChapterShowDialog: false,
      updateChapterdialogTitle: '批量编辑章节',
      updateQuestionShowDialog: false,
      updateQuestiondialogTitle: '编辑题目',
      updateQuestiondialogId: '',
      questions: [],
      updateChapterIds: [],
      chapters: [],
      currentRow: null,
      total: 0,
      searchQuery: '',
      id: null,
      difficulty: '3',
      type: '',
      fk_t_sctk_chapter_id: '',
      expandedRows: [],
      queryParams: {
        pageIndex: 0,
        pageSize: 10,
        type: '',
        fk_t_sctk_chapter_id: '',
        topic: '',
        keyword: ''
      },
      selectedRows: []
    }
  },
  methods: {
    handleClick(tab, event) {
    },
    changePageIndex(newPageIndex) {
      //切换页数
      this.queryParams.pageIndex = newPageIndex - 1
      this.getQuesstionBankList()
    },
    changePageSize(newPageSize) {
      //切换条数
      this.queryParams.pageSize = newPageSize
      //切换条数 页数默认置0
      this.queryParams.pageIndex = 0
      this.getQuesstionBankList()
    },
    async getQuesstionBankList() {

      const { data, total } = await getQuesstionBankList({ ...this.queryParams, fk_t_sctk_id: this.id });
      this.questions = data;
      this.total = total;
    },
    async getChapters() {
      let result = await getSctktChapterList({ fk_t_sctk_id: this.id })
      // 递归处理
      this.chapters = transListToTreeDataOnChapter(result, 0)
    },
    async addQuestion() {
      const result = await addQuestion({ /* 添加试题的数据 */ });
      if (result.success) {
        this.fetchQuestions();
      }
    },
    async handleEdit(index, row) {

      this.currentRow = row
      this.updateQuestionShowDialog = true
      this.updateQuestiondialogTitle = '编辑题目'
      this.updateQuestiondialogId = row.id
    },
    async handleDelete(index, row) {
      this.$confirm('确定要删除该题目吗？', '提示', {
        type: 'warning'
      })
        .then(async () => {
          await deleteQuestion({ id: row.id });
          this.$message.success('删除成功');
          this.getQuesstionBankList();
        })
    },
    searchQuestions() {
      // 实现搜索逻辑
      this.getQuesstionBankList()

    },
    handleRowClick(row, column, event) {
      if (this.expandedRows.includes(row.id)) {
        this.expandedRows = this.expandedRows.filter(id => id !== row.id);
      } else {
        this.expandedRows.push(row.id);
      }
    },
    typeName(type) {
      const typeMap = {
        1: '单选题',
        2: '多选题',
        3: '判断题',
        4: '填空题',
        5: '简答题'
      };
      return typeMap[type] || '未知';
    },
    difficultyName(difficulty) {
      const difficultyMap = {
        1: '简单',
        2: '容易',
        3: '适中',
        4: '困难',
        5: '极难',
      };
      return difficultyMap[difficulty] || '未知';
    },
    parseOptions(options) {
      if (typeof options === 'string') {
        try {
          options = JSON.parse(options);  // 把字符串转成数组
        } catch (e) {
          console.error('JSON解析失败', e);
          return [];
        }
      }
      if (!options || !Array.isArray(options)) {

        return [];
      }

      return options.map(option => ({
        key: option.key,
        value: option.value
      }));
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleCommand(command) {
      if (command === 'batchDelete') {
        this.batchDelete();
      } else if (command === 'batchUpdateChapter') {
        // 打开批量修改章节的对话框
        this.batchUpdateChapter()
      }
    },
    async batchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的题目');
        return;
      }
      this.$confirm('确定要删除选中的题目吗？', '提示', {
        type: 'warning'
      })
        .then(async () => {
          for (const row of this.selectedRows) {
            await deleteQuestion({ id: row.id });
          }
          this.$message.success('删除成功');
          this.getQuesstionBankList();
        });
    },
    batchUpdateChapter() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要更换章节的题目');
        return;
      }
      const ids = this.selectedRows.map(row => row.id);

      this.updateChapterIds = ids;
      this.updateChapterShowDialog = true;


    }

  }

}
</script>
<style scoped>
.app-container {
  margin: 10px;
  background: #fff;
  border-radius: 5px;
  padding: 10px;

  .title {
    display: block;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    /* 文字居中对齐 */
    margin-bottom: 10px;
    /* 给标题下方留出间距 */
    border-bottom: 1px solid #e8eaec;
  }

  .table {
    display: flex;
    align-items: center;
    /* 垂直居中 */
    justify-content: space-between;
    /* 把子元素分布在两侧 */
    flex-wrap: wrap;
    /* 如果空间不足可以换行 */
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .table>.left-tools {
    display: flex;
    align-items: center;
    gap: 10px;
    /* 控制按钮之间的间距 */
  }

  .search-container {
    display: inline-block;

  }


  .title-button {
    width: 120px;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .topic-container {
    max-width: 600px;
    /* 根据需要调整最大宽度 */
    word-break: break-all;
    /* 对长单词或 URL 地址进行强制换行 */
  }

  .no-bullets {
    list-style: none;
    padding-left: 0;
    word-break: break-all;
  }

  .option-item {
    margin-bottom: 5px;
    word-break: break-all;
    /* 调整这个值即可控制行间距 */
  }

  .pagination {
    margin-top: 20px;
  }





}
</style>
